# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging

from odoo import _, api, fields, models
from odoo.exceptions import UserError, ValidationError
from odoo.tools import float_compare, float_is_zero
from odoo.tools.misc import clean_context


class StockScrapExt(models.Model):
    _inherit = 'stock.scrap'

    scrap_type = fields.Selection([
        ('base', 'Base'),
        ('prod', 'Work Order Scrap')
    ], default='base', required=True, string="Scrap Type")
    scrap_line_ids = fields.One2many('stock.scrap.line', 'stockscrap_id', 'Stock Scrap List', copy=True)

    def action_validate(self):
        self.ensure_one()
        if sum(self.scrap_line_ids.mapped('qty_reject')) != self.scrap_qty:
            raise ValidationError(_('The total quantity on the scrap lines does not match the scrap quantity.'))
        res = super(StockScrapExt, self).action_validate()
        return res

    @api.onchange('production_id')
    def _onchange_production_id(self):
        for r in self:
            return {
                'domain': {
                    'workorder_id': [('id', 'in', r.production_id.workorder_ids)]
                }
            }

    def unlink(self):
        scrap_lines = self.env['stock.scrap.line'].search([('stockscrap_id', '=', self.id)])
        for l in scrap_lines:
            l.unlink()
        res = super(StockScrapExt, self).unlink()
        return res


class StockScrapLine(models.Model):
    _name = 'stock.scrap.line'
    _description = 'Stock Scrap Line'  # 报废明细

    stockscrap_id = fields.Many2one('stock.scrap', "Scrap Order")
    production_id = fields.Many2one('mrp.production', "Manufacturing Order", store=False)
    rep_workorder_id = fields.Many2one(
        'mrp.workorder', 'Responsible Work Order', domain="[('production_id', '=', production_id)]")
    scrapreason_ids = fields.Many2many('scrap.reason', store=False)
    scrapreason_id = fields.Many2one(
        'scrap.reason', string="Scrap Reason", ondelete='restrict', required=True, index=True)
    qty_reject = fields.Float(string='Scrap Quantity')

    @api.onchange('stockscrap_id')
    def _onchange_stockscrap_id(self):
        self.production_id = self.stockscrap_id.production_id

    @api.onchange('rep_workorder_id')
    def _onchange_rep_workorder_id(self):
        if self.rep_workorder_id:
            self.scrapreason_ids = self.rep_workorder_id.workcenter_id.scrapreason_ids
        else:
            self.scrapreason_ids = self.env['scrap.reason'].sudo()

    # @api.depends('product_id')
    # def _compute_product_uom_id(self):
    #     for scrap in self:
    #         scrap.product_uom_id = scrap.product_id.uom_id
    #
    # @api.depends('company_id', 'picking_id')
    # def _compute_location_id(self):
    #     groups = self.env['stock.warehouse']._read_group(
    #         [('company_id', 'in', self.company_id.ids)], ['company_id'], ['lot_stock_id:array_agg'])
    #     locations_per_company = {
    #         company.id: lot_stock_ids[0] if lot_stock_ids else False
    #         for company, lot_stock_ids in groups
    #     }
    #     for scrap in self:
    #         if scrap.picking_id:
    #             scrap.location_id = scrap.picking_id.location_dest_id if scrap.picking_id.state == 'done' else scrap.picking_id.location_id
    #         else:
    #             scrap.location_id = locations_per_company[scrap.company_id.id]
    #
    # @api.depends('company_id')
    # def _compute_scrap_location_id(self):
    #     groups = self.env['stock.location']._read_group(
    #         [('company_id', 'in', self.company_id.ids), ('scrap_location', '=', True)], ['company_id'], ['id:min'])
    #     locations_per_company = {
    #         company.id: stock_warehouse_id
    #         for company, stock_warehouse_id in groups
    #     }
    #     for scrap in self:
    #         scrap.scrap_location_id = locations_per_company[scrap.company_id.id]
    #
    # @api.depends('move_ids', 'move_ids.move_line_ids.quantity', 'product_id')
    # def _compute_scrap_qty(self):
    #     self.scrap_qty = 1
    #     for scrap in self:
    #         if scrap.move_ids:
    #             scrap.scrap_qty = scrap.move_ids[0].quantity
    #
    # @api.onchange('lot_id')
    # def _onchange_serial_number(self):
    #     if self.product_id.tracking == 'serial' and self.lot_id:
    #         message, recommended_location = self.env['stock.quant']._check_serial_number(self.product_id,
    #                                                                                      self.lot_id,
    #                                                                                      self.company_id,
    #                                                                                      self.location_id,
    #                                                                                      self.picking_id.location_dest_id)
    #         if message:
    #             if recommended_location:
    #                 self.location_id = recommended_location
    #             return {'warning': {'title': _('Warning'), 'message': message}}
    #
    # @api.ondelete(at_uninstall=False)
    # def _unlink_except_done(self):
    #     if 'done' in self.mapped('state'):
    #         raise UserError(_('You cannot delete a scrap which is done.'))
    #
    # def _prepare_move_values(self):
    #     self.ensure_one()
    #     return {
    #         'name': self.name,
    #         'origin': self.origin or self.picking_id.name or self.name,
    #         'company_id': self.company_id.id,
    #         'product_id': self.product_id.id,
    #         'product_uom': self.product_uom_id.id,
    #         'state': 'draft',
    #         'product_uom_qty': self.scrap_qty,
    #         'location_id': self.location_id.id,
    #         'scrapped': True,
    #         'scrap_id': self.id,
    #         'location_dest_id': self.scrap_location_id.id,
    #         'move_line_ids': [(0, 0, {
    #             'product_id': self.product_id.id,
    #             'product_uom_id': self.product_uom_id.id,
    #             'quantity': self.scrap_qty,
    #             'location_id': self.location_id.id,
    #             'location_dest_id': self.scrap_location_id.id,
    #             'package_id': self.package_id.id,
    #             'owner_id': self.owner_id.id,
    #             'lot_id': self.lot_id.id,
    #         })],
    #         # 'restrict_partner_id': self.owner_id.id,
    #         'picked': True,
    #         'picking_id': self.picking_id.id
    #     }

    # def do_scrap(self):
    #     self._check_company()
    #     for scrap in self:
    #         scrap.name = self.env['ir.sequence'].next_by_code('stock.scrap') or _('New')
    #         move = self.env['stock.move'].create(scrap._prepare_move_values())
    #         # master: replace context by cancel_backorder
    #         move.with_context(is_scrap=True)._action_done()
    #         scrap.write({'state': 'done'})
    #         scrap.date_done = fields.Datetime.now()
    #         if scrap.should_replenish:
    #             scrap.do_replenish()
    # return True

#    def do_replenish(self):
#        self.ensure_one()
#        self.with_context(clean_context(self.env.context)).env['procurement.group'].run([self.env['procurement.group'].Procurement(
#            self.product_id,
#            self.scrap_qty,
#            self.product_uom_id,
#            self.location_id,
#            self.name,
#            self.name,
#            self.company_id,
#            {}
#        )])
